package com.beiing.tianshuai.tianshuai.huodong;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.alipay.PayResult;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.ActiveInfoBean;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;

/**
 * Created by LZQ on 2018/1/30.
 */

public class PayActivity extends BaseActivity {

    @BindView(R.id.toolbar_iv_back)
    ImageView toolBarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView toolBarTitle;
    @BindView(R.id.tv_rest_time)
    TextView tvRestTime;
    @BindView(R.id.riv_cover)
    QMUIRadiusImageView rivCover;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_praise)
    TextView tvPraise;
    @BindView(R.id.rg_pay_type)
    RadioGroup rgPayType;
    @BindView(R.id.tv_pay)
    TextView tvPay;

    //支付宝支付部分
    private static final int SDK_PAY_FLAG = 1001;
    private String PSA_PRIVATE = "";

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    // 同步获取结果
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        showShortText("支付成功");
                    } else {
                        showShortText("支付失败");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_active_pay;
    }

    @Override
    protected void init() {
        initData();
        initListener();
    }

    private void initData() {
        toolBarIvBack.setVisibility(View.VISIBLE);
        toolBarTitle.setText("待支付");
        Intent intent = getIntent();
        ActiveInfoBean activeInfoBean = (ActiveInfoBean) intent.getSerializableExtra("activeInfo");
        LogUtils.i("photo", activeInfoBean.getCover());
        RequestOptions options = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .override(800, 450);
        Glide.with(getApplicationContext())
                .load(HttpRequestConstant.ACTIVITY_PIC_HEAD + activeInfoBean.getCover())
                .apply(options)
                .into(rivCover);
        tvTitle.setText(activeInfoBean.getTitle());
        tvNum.setText("1张");
        tvPraise.setText(String.format("￥%s", activeInfoBean.getPrice()));
    }

    private void initListener() {
        toolBarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int checkedRadioButtonId = rgPayType.getCheckedRadioButtonId();
                switch (checkedRadioButtonId) {
                    case R.id.rb_wechat_pay:
                        wechatPay();
                        break;
                    case R.id.rb_ali_pay:
                        aliPay();
                        break;
                    default:
                        showShortText("请选择支付方式");
                        break;
                }
            }
        });
    }

    /**
     * 支付宝支付
     */
    private void aliPay() {
        // 密钥验证的类型 true:RSA2 false:RSA
//        boolean rsa = false;
//        // 构造支付订单参数列表
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(AppConstant.AliPay_APP_ID, rsa);
//        // 构造支付订单参数信息
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//        // 对支付参数信息进行签名
//        String sign = OrderInfoUtil2_0.getSign(params, PSA_PRIVATE, rsa);
        // 订单信息
//        final String orderInfo = orderParam + "&" + sign;

        final String orderInfo = "alipay_sdk=alipay-sdk-php-20161101&amp;app_id=2018012802098633&amp;biz_content=%7B%22body%22%3A%22Iphone6+16G%22%2C%22subject%22%3A%22%27P%5Cu000f%22%2C%22out_trade_no%22%3A%2270501111111S001111119%22%2C%22total_amount%22%3A%220.1%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&amp;charset=UTF-8&amp;format=json&amp;method=alipay.trade.app.pay&amp;notify_url=http%3A%2F%2Fwww.tianshuai.com.cn%2FLibrary%2FLibrary%2Fhuidiao&amp;sign_type=RSA2&amp;timestamp=2018-01-30+16%3A20%3A21&amp;version=1.0&amp;sign=yvfIrlw6up5suc4B3I8NWQhIURPsTVaGEZ8w%2BjbW9bLeSdQb878PSk7ACHAsXGSu%2BBJOGL4ejcohPzHD9E7KhpVRcBq%2FqdfR65tLWGi7iQcvjS4UDygMbwktOgEjiE7hrnFR4ZwEcep2QMQ3sLuPy0yaEhkLPB7AT7fE4ybNKxMgd3wOrfBIlQaLdyjDTGHHwZMuRSRXY1czqNWn0GnwKvepEfYMxFl3cy6IJlcautFci9Y8z1nvxLx2ddrLXRSE4tm%2BSj9LLyNFBgb%2FNQqVcLb2GkagoOvhQnX2hZ0PIYpBWdNVvrUQCNY5oZZCUKXWtwMloJnX9RPpRY3PH7kWhg%3D%3D";
        // 异步处理
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 新建任务
                PayTask payTask = new PayTask(PayActivity.this);
                // 获取支付结果
                Map<String, String> result = payTask.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 微信支付
     */
    private void wechatPay() {
        IWXAPI api = WXAPIFactory.createWXAPI(this, AppConstant.WX_APP_ID, true);
        PayReq request = new PayReq();
        request.appId = AppConstant.WX_APP_ID;
        request.partnerId = "1493065452";                     // 商户号
        request.prepayId = "";                                // 预支付交易会话ID
        request.packageValue = "Sign=WXPay";                  // 扩展字段
        request.nonceStr = "";                                // 随机字符串
        request.timeStamp = "";                               // 时间戳
        request.sign = "";                                    // 签名
        api.sendReq(request);
    }
}
